#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
MCP服务反馈处理演示
展示如何在MCP服务中处理用户反馈并根据反馈调整服务行为
"""

import sys
import os

# 添加项目根目录到路径中
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from src.services.mcp_service import mcp_service_manager


def demo_mcp_feedback():
    """演示MCP服务反馈处理"""
    print("=== MCP服务反馈处理演示 ===\n")
    
    # 模拟服务器名称
    server_name = "filesystem"
    user_id = "user_123"
    
    print(f"1. 添加用户反馈到 {server_name} 服务")
    
    # 添加不同类型反馈
    feedbacks = [
        {
            "server_name": server_name,
            "user_id": user_id,
            "feedback": "文件读取速度较慢，特别是在处理大文件时",
            "feedback_type": "performance"
        },
        {
            "server_name": server_name,
            "user_id": user_id,
            "feedback": "有时会出现连接超时错误",
            "feedback_type": "error"
        },
        {
            "server_name": server_name,
            "user_id": user_id,
            "feedback": "希望增加文件压缩功能",
            "feedback_type": "suggestion"
        },
        {
            "server_name": server_name,
            "user_id": "user_456",
            "feedback": "界面可以更直观一些",
            "feedback_type": "general"
        }
    ]
    
    # 添加反馈
    for i, feedback_data in enumerate(feedbacks, 1):
        result = mcp_service_manager.add_feedback(
            server_name=feedback_data["server_name"],
            user_id=feedback_data["user_id"],
            feedback=feedback_data["feedback"],
            feedback_type=feedback_data["feedback_type"]
        )
        
        if result["success"]:
            print(f"  ✓ 反馈 {i} 添加成功 (ID: {result['feedback_id']})")
        else:
            print(f"  ✗ 反馈 {i} 添加失败: {result['error']}")
    
    print("\n2. 查看反馈历史")
    
    # 获取反馈历史
    feedback_history = mcp_service_manager.get_feedback_history(server_name)
    print(f"  {server_name} 服务共有 {len(feedback_history)} 条反馈:")
    
    for feedback in feedback_history:
        print(f"    - [{feedback['feedback_type']}] {feedback['feedback']} (用户: {feedback['user_id']})")
    
    print("\n3. 查看反馈摘要")
    
    # 获取反馈摘要
    feedback_summary = mcp_service_manager.get_feedback_summary(server_name)
    print(f"  服务器: {feedback_summary['server_name']}")
    print(f"  总反馈数: {feedback_summary['total_feedback']}")
    print("  按类型统计:")
    for feedback_type, count in feedback_summary['feedback_by_type'].items():
        print(f"    {feedback_type}: {count}")
    
    if feedback_summary['last_feedback']:
        last_fb = feedback_summary['last_feedback']
        print(f"  最新反馈: [{last_fb['feedback_type']}] {last_fb['feedback']} (用户: {last_fb['user_id']})")
    
    print("\n4. 处理反馈 (自动策略)")
    
    # 自动处理反馈
    process_result = mcp_service_manager.process_feedback(server_name, strategy="auto")
    
    if process_result["success"]:
        print(f"  ✓ 反馈处理成功: {process_result['message']}")
        if process_result.get("feedback_analysis"):
            print("  反馈分析:")
            for fb_type, count in process_result["feedback_analysis"].items():
                print(f"    {fb_type}: {count}")
        if process_result.get("actions_taken"):
            print("  采取的行动:")
            for action in process_result["actions_taken"]:
                print(f"    - {action}")
    else:
        print(f"  ✗ 反馈处理失败: {process_result['error']}")
    
    print("\n5. 处理反馈 (重启策略)")
    
    # 使用重启策略处理反馈
    process_result = mcp_service_manager.process_feedback(server_name, strategy="restart")
    
    if process_result["success"]:
        print(f"  ✓ 反馈处理成功: {process_result['message']}")
        if process_result.get("actions_taken"):
            print("  采取的行动:")
            for action in process_result["actions_taken"]:
                print(f"    - {action}")
    else:
        print(f"  ✗ 反馈处理失败: {process_result['error']}")
    
    print("\n=== 演示完成 ===")


if __name__ == "__main__":
    demo_mcp_feedback()